package com.example.springboot.controller;
import com.example.springboot.domain.DbBackup;
import com.example.springboot.domain.PageBean;
import com.example.springboot.domain.User;
import com.example.springboot.enums.ResCodeEnum;
import com.example.springboot.mapper.DBMapper;
import com.example.springboot.services.DBService;
import com.example.springboot.utils.ThreadLocalUtil;
import com.example.springboot.utils.ZIpUtil;
import com.example.springboot.vo.ResVO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Base64Util;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/db")
@Slf4j
public class DBController {

    @Value("${filePath}")
    String filePath;//源文件路径

    @Value("${dbData.dbName}")
    String dbName;//数据库名

    @Value("${zipPath}")
    String zipPath;//压缩文件路径

    @Autowired
    DBService dbService;

    @GetMapping(value = "/queryTables")
    public ResVO<List<String>> queryTables()  {
        //查找是否存在用户
        List<String> list=dbService.queryTables();
        //返回查找结果
        return new ResVO<>(1001, "查询成功", list);
    }

    @PostMapping(value = "/databasebackup")
    public ResVO<String> databasebackup(@RequestBody List<String> list) throws Exception {

        Boolean aBoolean = dbService.databasebackup(list);
        if(aBoolean){
            return new ResVO<String>(6001,"备份成功","");
        }else {
            return new ResVO<String>(6002,"备份失败","");
        }

    }




    @GetMapping(value = "/searchRecord")
    public ResVO<PageBean<DbBackup>> searchRecord( HttpServletRequest request){

        //接收前端参数
        Integer pageNum = Integer.parseInt(request.getParameter("pageNum"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        String name = request.getParameter("name");
        Integer type = Integer.parseInt(request.getParameter("type")) ;
        String createTime = request.getParameter("createTime");

        //参数处理
        int page=(pageNum-1)*pageSize;
        if(createTime!=null && createTime.length()>10){
            createTime=createTime.substring(0,10);
        }

        //后端业务处理
        PageBean<DbBackup> dbBackupPageBean=new PageBean<>();
        dbBackupPageBean=dbService.searchRecord(page,pageSize,name,type,createTime);

        //响应前端
        return new ResVO<>(1001,"查询成功",dbBackupPageBean);
    }


    @PostMapping (value = "/download")
    public void download(@RequestBody  List<Integer> idList, HttpServletResponse response){

        List<String> filePath=new ArrayList<>();
        if(idList.size()!=0){
            filePath = dbService.queryRecordByIdList(idList);
        }

        if(filePath.size()>0){
            String pathame= filePath.get(0);
            //头文件设置
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + pathame);
            byte[] buff = new byte[1024];
            BufferedInputStream bis = null;
            OutputStream os = null;
            try {
                os = response.getOutputStream();
                //获取扩展名
                bis = new BufferedInputStream(new FileInputStream(
                        new File(zipPath+pathame)));
                int i = bis.read(buff);
                //文件流响应
                while (i != -1) {
                    os.write(buff, 0, buff.length);
                    os.flush();
                    i = bis.read(buff);
                }
            } catch ( IOException e ) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @DeleteMapping(value = "/removeFile")
    public ResVO<String> removeFile(@RequestParam Map<String,Integer> map){

        List<Integer> idList=new ArrayList<>();
        for (String key : map.keySet()) {
            idList.add(map.get(key));
        }
        Boolean flag=dbService.removeFile(idList);
        if(flag){
            return new ResVO<>(3001,"删除成功","");
        }
        return new ResVO<>(3002,"删除失败","");
    }

    /**
     * 还原数据库
     */
    @GetMapping(value = "/rollBack")
    public ResVO<String> rollBack(HttpServletRequest request){
        String id = request.getParameter("dbid");

        Boolean aBoolean = dbService.rollBack(id);

        if(!aBoolean){
            return new ResVO<>(ResCodeEnum.UPDATEER.getResCode(), "恢复备份失败","");
        }

        return new ResVO<>(ResCodeEnum.UPDATEOK.getResCode(), "数据恢复成功","");
    }
}
